<template>
  <div class="settings-container">
    <van-form @submit="onSubmit" class="form-container">
      <!-- 显示头像 -->
      <div class="avatar-container">
        <img :src="userInfo.avatar" class="avatar" />
      </div>
      <van-field v-model="userInfo.username" label="用户名" disabled class="form-field" />
      <van-field v-model="userInfo.password" label="密码" type="password" class="form-field" />
      <van-field v-model="userInfo.email" label="邮箱" placeholder="请输入邮箱" class="form-field" />
      <van-button type="primary" native-type="submit" class="submit-button" block color="var(--gradient-primary)">保存修改</van-button>
      

    </van-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { UserControllerService } from '../../api/services/UserControllerService';
import { showToast } from 'vant';
import { useRouter } from 'vue-router'; // 新增路由导入

const router = useRouter(); // 初始化路由

const userInfo = ref({
  id: null,
  email: null,
  username: null,
  avatar: null,
  password: null
});

onMounted(async () => {
  try {
    const token = localStorage.getItem('token');
    if (token) {
      const res = await UserControllerService.getIdByToken(token);
      userInfo.value.id = res.data;
    } else {
      console.error('未获取到有效的 token');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
  getUserInfo()
});

const getUserInfo = async () => {
  try {
    const res = await UserControllerService.getUserById(userInfo.value.id);
    userInfo.value = res.data;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

const onSubmit = async () => {
  try {
    await UserControllerService.updateUser(userInfo.value);
    showToast('修改成功');
  } catch (error) {
    console.error('修改失败:', error);
    showToast('修改失败');
  }
};


</script>

<style scoped>
.settings-container {
  padding: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.form-container {
  background-color: #ffffff;
  padding: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.avatar-container {
  text-align: center;
  margin-bottom: 24px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.form-field {
  margin-bottom: 16px;
}

.submit-button {
  margin-top: 16px;
  border-radius: 8px;
}

.set {
  padding: 24px;
  border-radius: 8px;
}

.header {
  text-align: center;
  padding: 20px 0;
  top: 48px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.info-section {
  margin-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-span {
  margin-left: 10px;
}
</style>